package com.weic.manager.utils;

import com.weic.manager.user.vo.UserVO;
import com.weic.manager.vo.LoginInfo;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * web工具类实现类
 */
public class WebUtils {

    private static ThreadLocal<LoginInfo> loginInfoThreadLocal = new ThreadLocal<LoginInfo>();

    /**
     * 设置本地登入信息
     * @return
     */
    private static LoginInfo getLocalLoginInfo(){
        return loginInfoThreadLocal.get();
    }

    /**
     * 设置本地登入信息
     * @param loginInfo
     */
    private static void setLocalLoginInfo( LoginInfo loginInfo){
        loginInfoThreadLocal.set(loginInfo);
    }

    /**
     * 移除本地登入信息
     */
    private static void removeLocalLoginInfo(){
        loginInfoThreadLocal.remove();
    }

    /**
     * 设置登入信息
     * @param userVO
     */
    public static void setLoginInfo(UserVO userVO) {
        HttpServletRequest request = ServletContextHolder.getRequest();
        if(!ObjectUtils.isEmpty(request)){
            LoginInfo loginInfo = new LoginInfo();
            loginInfo.setUserVO(userVO);
            HttpSession session = request.getSession(true);
            session.setAttribute(Constants.LOGIN_INFO,loginInfo);
            //设置当前对象的现成局部变量
            setLocalLoginInfo(loginInfo);
        }
    }

    /**
     * 获取登入信息
     * @return
     */
    public static LoginInfo getLoginInfo() {
        LoginInfo loginInfo = getLocalLoginInfo();
        if(ObjectUtils.isEmpty(loginInfo)){
            HttpServletRequest request = ServletContextHolder.getRequest();
            HttpSession session = request.getSession();
            loginInfo = (LoginInfo)session.getAttribute(Constants.LOGIN_INFO);
        }
        return loginInfo;
    }

    /**
     * 移除登入信息
     */
    public static void remove(){
        removeLocalLoginInfo();
        ServletContextHolder.remove();
    }
}
